package com.bw.hxc.controller;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.hxc.entity.Result;
import com.bw.hxc.entity.User;
import com.bw.hxc.service.IUserService;
import com.bw.hxc.utils.JwtUtils;
import com.bw.hxc.utils.SmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 黄旭超
 * @since 2022-06-07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    IUserService userService;

    @RequestMapping("getSmsCode")
    public Result getSmsCode(@RequestBody User user){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("tel",user.getTel());
        User DBUser = userService.getOne(userQueryWrapper);
        if (DBUser == null){
            return new Result(201,"尚未注册","");
        }
        //生成随机数
        String code = RandomUtil.randomInt(1000, 9999) + "";
        //存入redis5分钟有效
        redisTemplate.opsForValue().set(user.getCodeKey(),code,5, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(user.getCodeKey()+"tel",user.getTel(),10,TimeUnit.MINUTES);
        try {
            SmsUtils.sendSms(user.getTel(),code);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(202,"验证码错误","");
        }
        return new Result(200,"验证码正确","");
    }

    @RequestMapping("mylogin")
    public Result mylogin(@RequestBody User user){
        //验证code
        if (!StringUtils.hasText(user.getCode()) || !StringUtils.hasText(user.getCodeKey())){
            return new Result(203,"请输入验证码","");
        }
        //验证code和tel
        String code = (String) redisTemplate.opsForValue().get(user.getCodeKey());
        String tel = (String) redisTemplate.opsForValue().get(user.getCodeKey()+"tel");
        if (!code.equals(user.getCode()) || !tel.equals(user.getTel())){
            new Result(204,"验证码不正确","");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("tel",user.getTel());
        User DBUser = userService.getOne(userQueryWrapper);
        if (DBUser == null){
            return new Result(201,"尚未注册","");
        }
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(DBUser.getUsername(), DBUser.getPassword());

        try {
            Authentication authenticate = authenticationManager.authenticate(upToken);

            String token = JwtUtils.createToken(DBUser.getCode(), 20, JSONUtil.toJsonStr(authenticate));

            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put("token",token);
            hashMap.put("userInfo",DBUser);
            return new Result(200,"",hashMap);
        }catch (Exception e){
            System.err.println("错误是："+e);
            return new Result(205,"错误","");
        }

    }

}
